package java1.myFile;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by asus on 2017/9/6.
 */
public final class myDirectory {
    public static File[] local(File dir, String regex) {
        return dir.listFiles(new FilenameFilter() {
            private Pattern pattern;

            @Override
            public boolean accept(File dir, String name) {
                return pattern.matcher(new File(name).getName()).matches();
            }
        });
    }

    public static class TreeInfo implements Iterable<File> {
        public List<File> files = new ArrayList<>();
        public List<File> dirs = new ArrayList<>();

        @Override
        public String toString() {
            return "TreeInfo{" +
                    "files=" + PPrint.pformat(files) +
                    ", dirs=" +  PPrint.pformat(dirs) +
                    '}';
        }

        @Override
        public Iterator<File> iterator() {
            return files.iterator();
        }

        void addAll(TreeInfo other) {
            files.addAll(other.files);
            dirs.addAll(other.dirs);
        }

        public static TreeInfo walk(String start) {
            return recurseDirs(new File(start), ".*");
        }

        static TreeInfo recurseDirs(File startDir, String regex) {
            TreeInfo info = new TreeInfo();
            for (File item : startDir.listFiles()) {
                if (item.isDirectory()) {
                    info.dirs.add(item);
                    info.addAll(recurseDirs(item, regex));
                } else {
                    info.files.add(item);
                }
            }
            return info;
        }

        public static void main(String[] args) {
            System.out.println(walk("."));
        }

    }

}
